package com.example.demo.Controller;

import com.example.demo.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2023-06-08
 * Time:22:46
 */

//@ResponseBody // 告诉程序我返回的是一个页面数据，而不是页面
//@Controller //让框架启动的时候加载当前类（只有加载的类别人才能使用(访问)）
//@Service // 五大类注解都可以，但是每个都是有自己的含义的，即使效果一样但是最好不要这样去做
//@RestController//RestController = ResponseBody + Controller
@RequestMapping("/test") //路由注册，不能省略
@Controller
@Slf4j
public class TestController {

    //    @RequestMapping("/hi")
    //指定当前方法只支持POST请求
//    @RequestMapping(value = "/hi",method = RequestMethod.POST)
//    @PostMapping("/hi") // 等于@RequestMapping(value = "/hi",method = RequestMethod.POST)
    @GetMapping("/hi") //等于@RequestMapping("/hi")
//都能实现映射的功能
    public String sayHi(String name,Integer v) {
        return "Hi:" + name + "  v:" + v;
    }


    @GetMapping("/num")
    public String GetName(Integer num){
        return "name: " + num;
    }

    //普通对象
    @GetMapping("/show-User")
    public String showUser(User user){
        return user.toString();
    }

    //接收json对象（和第三方系统通讯时常见的场景）
    @PostMapping("/show-jsonUser")//@RequestBody指定的就是接受一个json对象,需要配合PostMapping来使用
    public String showJsonUser(@RequestBody User user){
        return user.toString();
    }

    @GetMapping("/show-Time")
    public String showTime(@RequestParam("t") String startTime,
                           @RequestParam(value = "t2",required = false) String endTime){

        return "开始时间:" + startTime +" 结束时间:" + endTime ;
    }

    //从URL中直接获取参数
    @GetMapping("/login/{username}/{password}")
    public String login(@PathVariable("username") String username,
                        @PathVariable("password") String password){

        return username + " : " + password;
    }

    @RequestMapping("/show/{username}/and/{password}")
    public String showInfo(@PathVariable("password") String pwd,
                           @PathVariable("username") String username){
        return username + " : " + pwd;
    }

    @RequestMapping("/upfile")
    public String upfile(@RequestPart("myfile")MultipartFile file) throws IOException {
        String path = "D:\\Desktop\\img.png";
        //保存文件
        file.transferTo(new File(path));
        return path;
    }

    @RequestMapping("/myupfile")
    public String myupfile(@RequestPart("myupfile")MultipartFile file) throws IOException {
        //根目录
        String path = "D:\\Desktop\\CSDN封面图片\\";
        //根目录 + [唯一文件名]
        path += UUID.randomUUID().toString();
        //根目录 + 唯一文件名 + [后缀]
        //截取 . 之后的信息
        path += file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        file.transferTo(new File(path));
        return path;
    }


    @GetMapping("/getparam")
    //HttpServletRequest req 是spring boot/spring MVC 内置的，不用去传，当其项目启动的时候就直接注入了，不用传，本身就有
    //HttpServletRespond 同样也内置了
    public String getParam(HttpServletRequest req){
        return req.getParameter("username");
    }

    @RequestMapping("/getck")
    public String getCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        for (Cookie item:cookies){
            log.error(item.getName() + ":" + item.getValue());
        }
        return "get Cookie!";
    }

    @RequestMapping("/getck2")
    public String getCookie2(@CookieValue("awen") String val){
        return "Cookie value" + val;
    }

    @RequestMapping("/getUa")
    public String gerUa(@RequestHeader("user-agent") String userAgent){
        return userAgent;
    }

    @RequestMapping("/setsess")
    //存session
    public String setSession(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        session.setAttribute("userinfo","userinfo");
        return "Set Session Succeed";
    }

    @RequestMapping("/getsess")
    public String getSession(HttpServletRequest request){
        HttpSession session = request.getSession(false);//一定要加false
        if (session !=null && session.getAttribute("userinfo") != null){
            return (String) session.getAttribute("userinfo");
        }else {
            return "暂无 Session 信息";
        }
    }

    @RequestMapping("getsess2")
    //false 表示没有这个session也行
    public String getSession2(@SessionAttribute(value = "userinfo",required = false)String userinfo){
        return userinfo;
    }

    @RequestMapping("/respjson")
    public HashMap<String, String> respJson() {
        HashMap<String, String> map = new HashMap<>();
        map.put("Java", "Java Value");
        map.put("MySQL", "MySQL Value");
        map.put("Redis", "Redis Value");
        return map;
    }

    //请求转发方式1
    @RequestMapping("/fw")
    public String myForward() {
        return "forward:/hello.html";
    }

    //请求转发方式2
    @RequestMapping("/fw2")
    public void myForward2(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/hello.html").forward(request,response);
    }


    //请求重定向方式1
    @RequestMapping("/rd")
    public String myRedirect() {
        return "redirect:/hello.html";
    }

    //请求重定向方式2
    @RequestMapping("/rd2")
    public void myRedirect2(HttpServletResponse response) throws IOException {
        response.sendRedirect("/hello.html");
    }
}

